<?php

class Ssm extends MX_Controller {

	var $partials = array();
	var $sitePermissions = array();
	var $includes_path = '/includes';			 
	var $redirect = '/ssm/user';	
	var $num = 10;
	var $curr_language='english';
	var $userid=999;
	var $table = 'users';
	var $objectID = 'userID';			
	function __construct()
	{
		parent::__construct();

			// check user is logged in, if not send them away from this controller
		if (!$this->session->userdata('session_user'))
		{
			redirect('/admin/login/'.$this->core->encode($this->uri->uri_string()));
		}
	 
		// get permissions and redirect if they don't have access to this module
		if (!$this->permission->permissions)
		{
			redirect('/main/dashboard');
		}
		
		if (!($this->permission->permissions[$this->uri->segment(1)]['view']))
		{
			show_error('You do not have permission to view this page');
		}
		

		
		// load models and modules 	
		$this->load->model('ssm_model', 'ssm');
		$this->load->model('users_model', 'users');
		$this->load->module('pages');
		// load language demo 
		$this->load->language('english');
		
		 
		if($this->input->post('iLanguage')!=''){
			$this->curr_language = $this->input->post('iLanguage');
		}else{
			$this->session->set_userdata('language','english');
		}

	}

	//ssm
	function index()
	{	
		 $output=array();
		// display with cms layer
		 $this->view2('index.php', $output, TRUE);
	}
	
	function add_user(){
		// get values
		$output['data'] = $this->core->get_values($this->table);
		$output['groups'] = $this->permission->get_groups();		
		$output['grades'] = $this->ssm->get_grades();
		$output['label_language']=$this->curr_language;
		
		if (count($_POST)){
			$this->core->required = array(
			'username' => array('label' => 'Username', 'rules' => 'required|really_unique[users.username]|trim'),
			'email' => array('label' => 'Email', 'rules' => 'valid_email|unique[users.email]|trim'),
			'firstName' => array('label' => 'First name', 'rules' => 'required|trim|ucfirst'),
			'lastName' => array('label' => 'Last name', 'rules' => 'required|trim|ucfirst')
			);
			
			$this->core->set['dateCreated'] = date("Y-m-d H:i:s");

			if ($this->uploads->errors)
			 {
				$this->form_validation->set_error($this->uploads->errors);
			 }
		}
	
		// update
		if ($this->core->update($this->table) && count($_POST))
		{
			// where to redirect to
			redirect($this->redirect);
		}
  
		// templates
		$this->view2('add_user',$output);
	}
	
	function edit_user($userID)
	{
		// check permissions for this page
		//	//if (!in_array('users_edit', $this->permission->permissions) && $userID != $this->session->userdata('userID'))
		//{
		//	redirect('/admin/dashboard/permissions');
		//}

		// check this is a valid user
		if (!$user = $this->users->get_user($userID))
		{
			show_error('Not a valid user.');
		}

		// check they are not trying to edit a superuser
		if ($user['groupID'] < 0 && $this->session->userdata('groupID') >= 0)
		{
			show_error('You do have permission to edit this user.');
		}
		
		// set object ID
		$objectID = array($this->objectID => $userID);		

		// required
		$this->core->required = array(
			'username' => array('label' => 'Username', 'rules' => 'really_unique[users.username]|trim'),
			'email' => array('label' => 'Email', 'rules' => 'valid_email|unique[users.email]|trim'),
			'firstName' => array('label' => 'First name', 'rules' => 'trim|ucfirst'),
			'lastName' => array('label' => 'Last name', 'rules' => 'trim|ucfirst')
		);

		// get values
		$output['data'] = $this->core->get_values($this->table, $objectID);
		$output['groups'] = $this->permission->get_groups();			
		$output['grades'] = $this->ssm->get_grades();
		$output['label_language']=$this->curr_language;
		
		// deal with post
		if (count($_POST))
		{
			// set date
			$this->core->set['dateModified'] = date("Y-m-d H:i:s");
	
			// check groupID is not being overridden
			if (($this->input->post('groupID') && @!in_array('users_groups', $this->permission->permissions)) || ($this->input->post('groupID') < 0 && $this->session->userdata('groupID') >= 0))
			{
				redirect('/admin/dashboard/permissions');
				die();
			}
	
			// set siteID
			if ($this->input->post('siteID') && $this->session->userdata('groupID') < 0)
			{
				//$this->core->set['siteID'] = $this->input->post('siteID');
			}
			else
			{
				//$this->core->set['siteID'] = $this->siteID;
			}

			// update
			//if ($this->core->update($this->table, $objectID))
			//{
			//	$output['message'] = '<p>Your details have been updated.</p>';
			//}
		}	
		
		// templates
 
		$this->view2('edit_user',$output);
 
	}
	function edit_group($groupID)
	{
		// check permissions for this page
		//if (!in_array('users_groups', $this->permission->permissions))
		//{
		//	redirect('/admin/dashboard/permissions');
		//}	
				
		// set object ID
		$objectID = array('groupID' => $groupID);		

		// required
		$this->core->required = array(
			'groupName' => array('label' => 'Group name', 'rules' => 'required'),
		);

		// deal with post
		if (count($_POST))
		{			
			// check groupID is not being overridden
			if ($this->input->post('groupID') < 0 && $this->session->userdata('groupID') >= 0)
			{
				redirect('/admin/dashboard/permissions');
				die();
			}

			// update
			if ($this->core->update('permission_groups', $objectID))
			{
				// add permissions
				$this->permission->add_permissions($groupID, $this->siteID);
								
				// where to redirect to
				redirect('/admin/users/groups');
			}			
		}
				
		// get values
		$output['data'] = $this->core->get_values('permission_groups', $objectID);

		// get permissions
		$output['permissions'] = $this->permission->get_permissions($this->session->userdata('groupID'));

		// populate permissions
		$perms = $this->permission->get_permission_map($groupID);
		foreach ((array)$perms as $perm)
		{
			$output['data']['perm'.$perm['permissionID']] = 1;
		}
		
		 
		$this->view2('edit_group',$output);
		 
	}
	
	function add_group()
	{
		// check permissions for this page
		//if (!in_array('users_groups', $this->permission->permissions))
		//{
		//	redirect('/admin/dashboard/permissions');
		//}	

		// required
		$this->core->required = array(
			'groupName' => array('label' => 'Group name', 'rules' => 'required'),
		);

		// deal with post
		if (count($_POST))
		{			
			// check groupID is not being overridden
			if ($this->input->post('groupID') < 0 && $this->session->userdata('groupID') >= 0)
			{
				//redirect('/admin/dashboard/permissions');
				//die();
			}

			// update
			if ($this->core->update('permission_groups'))
			{
				// get new groupID
				$groupID = $this->db->insert_id();
				
				// add permissions on new groupID
				$this->permission->add_permissions($groupID, $this->siteID);
								
				// where to redirect to
				redirect('/admin/users/groups');
			}			
		}
				
		// get values
		$output['data'] = $this->core->get_values('permission_groups');

		// get permissions
		$output['permissions'] = $this->permission->get_permissions($this->session->userdata('groupID'));
		
		// templates
		
		$this->view2('add_group',$output);
		
	}
	
	function classlevel(){
 
			// check permissions for this page
		if (!($this->permission->permissions[$this->uri->segment(1)]['view']))
		{
			show_error('You do not have permission to view this page');
		}
		
		
		$output['btnAddClass']=$this->lang->line('ssm_class_addbuton');
		$output['status']=$this->lang->line('ssm_class_col_status');
		$output['createdate']=$this->lang->line('ssm_class_col_createdate');
		$output['edit']=$this->lang->line('ssm_class_col_edit');
		$output['del']=$this->lang->line('ssm_class_col_del');
		
		//Language
		$output['label_language']=$this->curr_language;
		
		$output['editImg'] = img(array('src'=> $this->config->item('staticPath').'/static/images/btn_edit.png'));

		
		if ($clevel = $this->ssm->get_school_grade())
		{
			$output['classlevel']=$clevel;
		
		}else{
		
			$output['classlevel']='';
		}
		 
		$this->view2('classlevel',$output ,TRUE );
 
	}
	
	function classdetail(){
		
		if($this->input->post('sid')!='' && $this->input->post('gid')!=''&& $this->input->post('schid')!=''){
			$sid=$this->input->post('sid') ;
			$gid=$this->input->post('gid') ;
			$schid=$this->input->post('schid') ;
			if ($clevel = $this->ssm->get_school_grade($gid,$sid,$schid)){
				echo json_encode($clevel);
	
			}else{
				echo json_encode(array("flag"=>0,"msg"=>"Data not found!!"));
			}
			
		}else {
			echo json_encode(array("flag"=>0,"msg"=>"incorrect data!!"));
		}
	}
	function del_class(){
		if (count($_POST)){
			$sid=$this->input->post('sid') ;
			$gid=$this->input->post('gid') ;
			$schid=$this->input->post('schid') ;
			$data['status']='N';
			$data["updated_by"]=$this->userid;
			$data["updated_date"]=date( "Y/m/d H:i:s" );
			
			if ($this->ssm->update_class($sid,$gid, $schid, $data)){
				 echo "Success";			 
			}else{
	 			echo "Fail";
			}
		}
		
	}
	function add_class(){
		if ($this->input->post('data') !=''){
			
		
			$data=$this->input->post('data');
			$data['grade_id'] = $this->ssm->get_last_grade_id($data['section_id'],1);
			$data['status'] = 'Y';
			$data['school_id'] = 1;
			$data["updated_by"]=$this->userid;
			$data["updated_date"]=date( "Y/m/d H:i:s" );
			 
			 if ($this->ssm->add_class($data)){
			  	echo "Success";		
			  }else{
	 
			  	echo "Fail";
			 }
		}
	}
	function update_class(){
		if (count($_POST)){
			$sid=$this->input->post('sid') ;
			$gid=$this->input->post('gid') ;
			$schid=$this->input->post('schid') ;
			$data=$this->input->post('data') ;
			$data["updated_by"]=$this->userid;
			$data["updated_date"]=date( "Y/m/d H:i:s" );
			
			if ($this->ssm->update_class($sid,$gid, $schid, $data)){
			  	echo "Success";		
			}else{
	 
				echo "Fail";
			}
		}
	}
	
	function user(){
	
	// check permissions for this page
	//	if (!in_array('users', $this->permission->permissions))
		//{
		//	redirect('/admin/dashboard/permissions');
		//}
		
		// if search
		$where = '';
		if (count($_POST) && ($query = $this->input->post('searchbox')))
		{
			$name = @preg_split('/ /', $query);
			if (count($name) > 1)
			{
				$firstName = $name[0];
				$lastName = $name[1];
				
				$where = '(email LIKE "%'.$this->db->escape_like_str($query).'%" OR firstName LIKE "%'.$this->db->escape_like_str($firstName).'%" AND lastName LIKE "%'.$this->db->escape_like_str($lastName).'%")';
			}
			else
			{
				$where = '(email LIKE "%'.$this->db->escape_like_str($query).'%" OR firstName LIKE "%'.$this->db->escape_like_str($query).'%" OR lastName LIKE "%'.$this->db->escape_like_str($query).'%")';
			}
		}

		// output users
		$output = $this->core->viewall('users', $where);

		// get admin groups
		if ($adminGroups = $this->permission->get_groups('admin'))
		{
			foreach($adminGroups as $group)
			{
				$output['adminGroups'][] = $group['groupID'];
			}
		}

		// get normal groups
		if ($normalGroups = $this->permission->get_groups('normal'))
		{
			foreach($normalGroups as $group)
			{
				$output['normalGroups'][] = $group['groupID'];
			}
		}
		
		// get all groups
		if ($userGroups = $this->permission->get_groups())
		{
			foreach($userGroups as $group)
			{
				$output['userGroups'][$group['groupID']] = $group['groupName'];
			}
		}
		
		$this->view2('user',$output ,TRUE );
	}
	function usergroup(){
	
		$output['status']='Status';
		$output['createdate']='Created Date';
		$output['edit']='Edit';
		$output['del']='Del';
		
		if ($argroup = $this->ssm->get_all_data('permission_groups'))
		{
			$output['group']=$argroup;
		
		}else{
		
		
		}
		 
		$this->view2('group',$output ,TRUE );
	}

	function schinfo(){
		$output['title']=$this->lang->line('ssm_schinfo_title');
		
		$this->view2('schinfo',$output ,TRUE );
	}
	function schmgmt(){
		$output['title']=$this->lang->line('ssm_schmgmt_title');
		$output['menu_info'] = $this->lang->line('ssm_schmgmt_mnu_info');
		$output['menu_grade'] = $this->lang->line('ssm_schmgmt_mnu_grade');
		$output['menu_classteacher'] = $this->lang->line('ssm_schmgmt_mnu_classteacher');
		
		$this->view2('schmgmt',$output ,TRUE );
	}
	function logging()
	{
		// logout if not admin
		if (!$this->session->userdata('session_admin'))
		{
			//redirect('/admin/login/'.$this->core->encode($this->uri->uri_string()));
		}
		
	 	$output=array();
		$this->view2('historylog',$output);
 
	}

	function logging_ajax()
	{
		// logout if not admin
		//if ($this->session->userdata('session_admin'))
		//{		
			$output = $this->core->viewall('tracking', null, array('trackingID', 'desc'));
	
			$this->load->view('history_ajax', $output);
		//}
	}
	function cbosection(){
		
		if ($section=$this->ssm->get_cbo_school_scection($this->curr_language)){
			//$data['json']=$section;
			 
			// $this->output->set_content_type('application/json')->set_output(json_encode($data));
			 echo json_encode($section);
			 exit();
		}
		else{
			echo '';
		}
		  
	}
    
    
	function view($view_name,$output,$flag='') 
	{	
		//header
		$this->load->view($this->includes_path.'/header');
		//echo "view=".$view_name;
		//Body
		$this->view_template($view_name,$output,$flag);
		//$this->load->view($view_name,$output);
		//Footer
 		$this->load->view($this->includes_path.'/footer');

	}
	function view2($view_name,$output,$flag='') 
	{	
		//header
		$this->load->view($this->includes_path.'/header');
		//echo "view=".$view_name;
		//Body
		//$this->view_template($view_name,$output,$flag);
		$this->load->view($view_name,$output);
		//Footer
 		$this->load->view($this->includes_path.'/footer');

	}
	function view_template($page, $sendthru = '', $module = FALSE, $return = FALSE)
	{	
		// set default parse file
		$parseFile = 'default';
		
		// handle web form
		if (count($_POST) && !$module)
		{
			if ($message = $this->core->web_form())
			{
				$sendthru['message'] = $message;
				$this->template->template['message'] = $sendthru['message'];
			}
			else
			{
				$sendthru['errors'] = validation_errors();
				$this->template->template['errors'] = $sendthru['errors'];
			}
		}

		// see if the cms is to generate a page from a module or a function of the site
		if ($module)
		{
			// set template tag
			$this->template->template['page:template'] = $page;
			
			// get module name
			$module = (is_string($module)) ? $module : $this->uri->segment(1);

			// get module template
			if ($file = @file_get_contents(APPPATH.'modules/'.$module.'/views/templates/'.$page.'.php'))
			{	
				// make a template out of the file
				$module = $this->template->generate_template(FALSE, $file);

				// merge the sendthru data with page data		
				$template = (is_array($sendthru)) ? array_merge($module, $sendthru) : $module;

				// set a null title
				$template['page:title'] = (!isset($sendthru['page:title'])) ? $this->site->config['siteName'] : $sendthru['page:title'];


				// output data
				if ($return === FALSE)
				{
					$this->parser->parse($parseFile, $template);
				}
				else
				{
					return $this->parser->parse($parseFile, $template, TRUE);
				}
			}
			else
			{
				show_error('Templating error!');
			}
		}
		else
		{
			show_404();
		}		
	}

}